package wine.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import wine.ejb.utilities.Constants;
import wine.ejb.utilities.Log;
import wine.ejb.utilities.LookupRemote;
import wine.ejb.utilities.Utility;
import wine.logic.entity.WSysUrl;
import wine.logic.entity.WUsrInf;

public class SecurityFilter extends LookupRemote implements Filter{
	protected FilterConfig filterConfig = null;
	private List<String> publicUrl;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		publicUrl=Utility.getStrLstForStr(filterConfig.getInitParameter("publicUrl"));
	}
	@Override
	public void destroy() {
		this.filterConfig = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		/* 获取request */
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		HttpServletResponse rep = (HttpServletResponse) response;
		String action = req.getRequestURI();
		String ctxpath = req.getContextPath();
		Log.debug(action);
		Log.debug(ctxpath);
		action = action.substring(action.indexOf(ctxpath) + ctxpath.length());
		WSysUrl sysUrl = getWSysUrlDao().countURL(action);
		
		if(publicUrl != null && publicUrl.contains(action)){
			filterChain.doFilter(request, response);
			return;
		}
		/*
		 * 将 url 写入 sys_url 表
		 * 如果 访问级别==0 ，就通过
		 */
		if(sysUrl == null || sysUrl.getPmsLevel()== Constants.PUBLIC_PMS_LEVEL){
			filterChain.doFilter(request, response);
			return;
		}
		WUsrInf usr = (WUsrInf) session.getAttribute(Constants.LOGIN_USER_INFO);
		if(usr == null){
			rep.reset();
			rep.sendRedirect(ctxpath + "/login.html");
			return;
		}
		boolean found = false;
		
		if(!found){
			rep.reset();
			rep.sendRedirect(ctxpath + "/err_600.jsp");
			return;
		}
		filterChain.doFilter(request, response);
	}
}
